package com.why.amallrest.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.jwt.JWT;
import com.why.amallrest.param.UserLoginParam;
import com.why.amallrest.uitl.RestCommonUtils;
import com.why.common.utils.HttpStatus;
import com.why.common.utils.PageUtils;
import com.why.common.utils.Result;
import com.why.entity.UsersEntity;
import com.why.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * 用户
 *
 * @author why
 * @email 1585049082@qq.com
 * @date 2021-10-24 20:16:08
 */
@RestController
@RequestMapping("mall/users")
@Slf4j
public class UsersController {
    @Autowired
    private UsersService usersService;

    @Value("mall.user.token.key")
    private String salt;

    @RequestMapping("login")
    public Result login(@RequestBody @Valid UserLoginParam user, BindingResult bindingResult) {
        log.info(user + "");
        if (bindingResult.hasErrors()) {
            Result result = Result.error();
            for (FieldError error : bindingResult.getFieldErrors()) {
                String message = error.getDefaultMessage();
                String field = error.getField();
                result.put(field, message);
            }
            return result;
        }
        UsersEntity entity = new UsersEntity();
        BeanUtils.copyProperties(user, entity);
        entity = usersService.loginCheck(entity);
        if (entity == null) {
            return Result.error("账号或者密码错误！请检查！");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("name", entity.getNickname() == null ? entity.getUsername() : entity.getNickname());
        data.put("userId", entity.getUserId());
        data.put("userImg",entity.getUserImg());

        String token = RestCommonUtils.generateJwtToken(data, salt);
        return Result.ok().put("token", token).put("data", data);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public Result list(@RequestParam Map<String, Object> params) {
        PageUtils page = usersService.queryPage(params);

        return Result.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")

    public Result info(@PathVariable("userId") Long userId) {
        UsersEntity users = usersService.getById(userId);

        return Result.ok().put("users", users);
    }

    /**
     * 登录
     */
    @RequestMapping("/register")

    public Result save(@RequestBody @Valid UserLoginParam user, BindingResult bindingResult) {
        log.info(String.valueOf(user));
        if (bindingResult.hasErrors()) {
            Result result = Result.error();
            for (FieldError error : bindingResult.getFieldErrors()) {
                String message = error.getDefaultMessage();
                String field = error.getField();
                result.put(field, message);
            }
            return result;
        }
        UsersEntity entity = new UsersEntity();
        BeanUtils.copyProperties(user, entity);
        String password = entity.getPassword();

        //密码加盐
        String slatPassword = MD5.create().setSalt(salt.getBytes()).digestHex(password);
        entity.setPassword(slatPassword);
        int count = usersService.userRegister(entity);
        if (count == 1) {
            return Result.ok("注册成功!");
        }

        return Result.error("注册失败,该用户名已经存在！");
    }


    /**
     * 修改
     */
    @RequestMapping("/update")

    public Result update(@RequestBody UsersEntity users) {
        usersService.updateById(users);

        return Result.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public Result delete(@RequestBody Long[] userIds) {
        usersService.removeByIds(Arrays.asList(userIds));

        return Result.ok();
    }

}
